package com.anyikang.volunteer.sos.volunteer.baidu;

import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyApplication;
import com.anyikang.volunteer.sos.volunteer.app.MyConstant;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyCurrentOrder;
import com.anyikang.volunteer.sos.volunteer.app.bean.ReceiveOrderJson;
import com.anyikang.volunteer.sos.volunteer.app.bean.TaskOrder;
import com.anyikang.volunteer.sos.volunteer.app.bean.User;
import com.anyikang.volunteer.sos.volunteer.app.main.MainActivity;
import com.anyikang.volunteer.sos.volunteer.utils.MyErrorDeal;
import com.anyikang.volunteer.sos.volunteer.utils.ToastUtils;
import com.anyikang.volunteer.sos.volunteer.utils.okhttputils_callback.StringDialogCallback;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.navisdk.adapter.BNRouteGuideManager;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class BaiduNavActivity extends AppCompatActivity implements FragmentNav.OnFragmentInteractionListener,FragmentSosInfo.OnFragmentInteractionListener,View.OnClickListener {

    private TextView tvNavShow;
    private TextView tvHelpShow;
    FragmentManager fm;
    String sosPersonId = null;
    String taskItemId = null;
    String TAG="BaiduNavActivity";
    Button btRight;
    TextView tvTitle;
    private LocationService locationService;
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;  //我的当前位置
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
    private Handler mHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLastIntent();
        setContentView(R.layout.baidu_nav);

        MainActivity.activityList.add(this);
        fm = this.getSupportFragmentManager();

        initView();
        initData();

    }


    /**
     * 查询任务单当前状态， //1表示需要救助，2救助中，3已完成   isSelfReceive是否自己已救
     */
    public void selectTaskState()
    {
        User user = new User(this);
        String token = user.getUserToken();

        OkHttpUtils
                .get(MyConstant.API_GET_TASK_STATE)//
                .tag(MyConstant.API_GET_TASK_STATE)//
                .params("tokenId", token)//
                .params("itemId", taskItemId)//
                .execute(new StringDialogCallback(BaiduNavActivity.this) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        int retCode = response.code();
                        if(retCode == 200)
                        {

                            Log.i(TAG,"onSuccess 200 return："+s);
                            try
                            {
                                JSONObject selectTaskOrder = new JSONObject(s);
                                int status = selectTaskOrder.getInt("status");

                                if(status == 1)//查询成功
                                {
                                     JSONObject data = selectTaskOrder.getJSONObject("data");
                                     int taskOrderState = data.getInt("state");
                                    switch (taskOrderState)
                                    {
                                        case 1:   //需要救助
                                            tvTitle.setText("需要救助");
                                            btRight.setText("我来救");
                                            Log.i(TAG,"需要救助");
                                            btRight.setVisibility(View.VISIBLE);
                                            break;
                                        case 2:  //救助中
                                            boolean isSelfReceive = data.getBoolean("isSelfReceive");
                                            if(isSelfReceive)
                                            {
                                                tvTitle.setText("我在救助");
                                                Log.i(TAG,"我在救助");
                                            }
                                            else
                                            {
                                                tvTitle.setText("已有人救");
                                                Log.i(TAG,"已有人救");
                                            }

                                            btRight.setVisibility(View.GONE);
                                            break;
                                        case 3: //已完成
                                            tvTitle.setText("救助已完成");
                                            Log.i(TAG,"救助已完成");
                                            btRight.setVisibility(View.GONE);
                                            break;
                                    }

                                }
                                else {
                                    //查询失败
                                    String msg = selectTaskOrder.getString("msg");
                                    MyErrorDeal.dealError(msg,BaiduNavActivity.this);
                                    btRight.setVisibility(View.GONE);
                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            MyErrorDeal.dealHttpError(response,BaiduNavActivity.this);
                            Log.i(TAG,"onSuccess "+retCode+"return: "+s);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

                        MyErrorDeal.dealHttpError(response,BaiduNavActivity.this);

                    }
                });
        return;



    }
    /**
     * 去查询任务单状态
     */
    private void initData() {


        selectTaskState();



    }


    public void getLastIntent() {
        Intent i = this.getIntent();
        Bundle b = i.getExtras();
        if(b != null)
        {
            sosPersonId = b.getString("sosPersonId");
            if(TextUtils.isEmpty(sosPersonId))
            {
                MyCurrentOrder currentOrder = new MyCurrentOrder(BaiduNavActivity.this);
                sosPersonId = currentOrder.getSosPersonId();

            }


            taskItemId = b.getString("taskItemId");
            Log.i(TAG,"sosPersonId="+sosPersonId+",taskItemId="+taskItemId);
        }
        return;
    }

    @Override
    public void onBackPressed() {

        Log.i(TAG,"onBackPressed");
        BNRouteGuideManager.getInstance().onBackPressed(false);

       //gxw- super.onBackPressed();
    }

    private void initView() {
        //标题
         tvTitle = (TextView) this.findViewById(R.id.tv_title);
        int colorWhtie = this.getResources().getColor(R.color.white);
        tvTitle.setTextColor(colorWhtie);
        tvTitle.setText("");

        ImageButton imgBtLeft = (ImageButton) this.findViewById(R.id.imgBtLeft);
        imgBtLeft.setOnClickListener(this);

        btRight= (Button) this.findViewById(R.id.btRight);

        btRight.setOnClickListener(this);

        tvNavShow = (TextView) this.findViewById(R.id.tvNavShow);
        tvHelpShow = (TextView) this.findViewById(R.id.tvHelpShow);
        tvNavShow.setOnClickListener(this);
        tvHelpShow.setOnClickListener(this);
        initNavFragmentShow();

    }
    public void initNavFragmentShow()
    {
        FragmentTransaction ft = fm.beginTransaction();
        Fragment fragmentNav = fm.findFragmentById(R.id.fragmentNav);
        FragmentSosInfo fragmentHelp = (FragmentSosInfo) fm.findFragmentById(R.id.fragmentHelp);
        fragmentHelp.setSosPersonId(sosPersonId);
        ft.show(fragmentNav);
        ft.hide(fragmentHelp);
        ft.commit();
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    public void showNav()
    {
        int colorWhite = this.getResources().getColor(R.color.white);
        int colorRed = this.getResources().getColor(R.color.colorPrimary);
        int colorGray = this.getResources().getColor(R.color.main_bg);
        int colorBlack =  this.getResources().getColor(R.color.text_title);
        tvNavShow.setBackgroundColor(colorRed);
        tvNavShow.setTextColor(colorWhite);

        tvHelpShow.setBackgroundColor(colorGray);
        tvHelpShow.setTextColor(colorBlack);

        FragmentTransaction ft = fm.beginTransaction();
  /*      ft.setCustomAnimations(android.R.animator.fade_in,
                android.R.animator.fade_out);*/

        Fragment fragmentNav = fm.findFragmentById(R.id.fragmentNav);
        Fragment fragmentHelp = fm.findFragmentById(R.id.fragmentHelp);

        if (fragmentNav.isHidden()) {
            ft.show(fragmentNav);
            ft.hide(fragmentHelp);
            ft.commit();
          //gxw-  button.setText("Hide");
        }
        else
        {
            ;
        }
        return;
    }


    public void showHelp()
    {
        int colorWhite = this.getResources().getColor(R.color.white);
        int colorRed = this.getResources().getColor(R.color.colorPrimary);
        int colorGray = this.getResources().getColor(R.color.main_bg);
        int colorBlack =  this.getResources().getColor(R.color.text_title);
        tvHelpShow.setBackgroundColor(colorRed);
        tvHelpShow.setTextColor(colorWhite);

        tvNavShow.setBackgroundColor(colorGray);
        tvNavShow.setTextColor(colorBlack);


        FragmentTransaction ft = fm.beginTransaction();
  /*      ft.setCustomAnimations(android.R.animator.fade_in,
                android.R.animator.fade_out);*/

        Fragment fragmentNav = fm.findFragmentById(R.id.fragmentNav);
        Fragment fragmentHelp = fm.findFragmentById(R.id.fragmentHelp);

        if (fragmentHelp.isHidden()) {
            ft.show(fragmentHelp);
            ft.hide(fragmentNav);
            ft.commit();
            //gxw-  button.setText("Hide");
        } else {
            //gxw-ft.hide(fragment);
            //gxw-button.setText("Show");
        }

        return;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.imgBtLeft:
                BaiduNavActivity.this.finish();
                break;
            case R.id.btRight:

                receiveOrder();
                break;
            case R.id.tvNavShow:
                showNav();
                break;

            case R.id.tvHelpShow:
                if(!TextUtils.isEmpty(sosPersonId))
                {
                    showHelp();
                }
                else
                {
                    ToastUtils.showToast(BaiduNavActivity.this,"接单后才可查看求救人详细信息");
                }
                break;
        }

    }




    /**
     * 处理接单成功
     */
    public void dealRecvOrderOk(TaskOrder data)
    {
        String itemId = data.getItemId();
        String sosPersonId = data.getSosPersonId();
        String deviceIMEI = data.getDeviceIMEI();
        double latitude = Double.parseDouble(data.getLatitude());  //gps坐标
        double longitude = Double.parseDouble(data.getLongitude());


        //因为接单的瞬间，求救人的位置会有变化，因此要刷新mTaskOrder中的经纬度等值（要gps转百度）
      /* gxw-导航页不需有和首页不一样 LatLng convertLatlng = BaiduMapUtils.convertGps2Map(latitude,longitude); //转换为百度坐标
        mTaskOrder.setItemId(itemId);
        mTaskOrder.setSosPersonId(sosPersonId);
        mTaskOrder.setDeviceIMEI(deviceIMEI);
        mTaskOrder.setLatitude(String.valueOf(convertLatlng.latitude));
        mTaskOrder.setLongitude(String.valueOf(convertLatlng.longitude));*/

        //保存接受的任务单 信息
        MyCurrentOrder currentOrder = new MyCurrentOrder();
        ContentValues curOrderValues = new ContentValues();
        curOrderValues.put("itemId",itemId);
        curOrderValues.put("state",2);  //我在救助中
        curOrderValues.put("deviceIMEI",deviceIMEI);
        curOrderValues.put("sosPersonId",sosPersonId);
        currentOrder.saveCurOrderInfo(BaiduNavActivity.this,curOrderValues);//保存住当前接受的任务单，用于现场图片上传（先接单才上传）

     /*   pushLayout.setVisibility(View.GONE);  //接单成功就隐藏那个任务单提示框，直接跳到导航页面
        if (BaiduNaviManager.isNaviInited()) {
            routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL,convertLatlng);  //原生GPS坐标类型
        }*/

        //gxw-暂时不需要，因为一接单就跳到导航页面去了，不需要再刷新sos位置startRefreshSosLoc();
        //但是要开始实时上报自己的位置了
        MyApplication.isRecvingOrder = true; //表示已接单并且正在救助中，开始连续上报自己的位置，至于连续获取SOS求救人的位置是放在了onhidden里。因为接受任务单后
        //，势必要调到导航页，因此刷新SOS位置就没有意义了，只有回到地图首页执行onhidden时hidden = false时，去更新SOS求救人位置才是有意义的。
        addMyLocationLayer();

        tvTitle.setText("我在救助中");
        btRight.setVisibility(View.GONE);


        return;
    }



    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                StringBuffer sb = new StringBuffer(256);
                sb.append("time : ");
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */
                sb.append(location.getTime());
                sb.append("\nlocType : ");// 定位类型
                sb.append(location.getLocType());
                sb.append("\nlocType description : ");// *****对应的定位类型说明*****
                sb.append(location.getLocationDescribe());
                sb.append("\nlatitude : ");// 纬度
                sb.append(location.getLatitude());
                sb.append("\nlontitude : ");// 经度
                sb.append(location.getLongitude());
                sb.append("\nradius : ");// 半径
                sb.append(location.getRadius());
                sb.append("\nCountryCode : ");// 国家码
                sb.append(location.getCountryCode());
                sb.append("\nCountry : ");// 国家名称
                sb.append(location.getCountry());
                sb.append("\ncitycode : ");// 城市编码
                sb.append(location.getCityCode());
                sb.append("\ncity : ");// 城市
                sb.append(location.getCity());
                sb.append("\nDistrict : ");// 区
                sb.append(location.getDistrict());
                sb.append("\nStreet : ");// 街道
                sb.append(location.getStreet());
                sb.append("\naddr : ");// 地址信息
                sb.append(location.getAddrStr());
                sb.append("\nDirection(not all devices have value): ");
                sb.append(location.getDirection());// 方向
                sb.append("\nlocationdescribe: ");
                sb.append(location.getLocationDescribe());// 位置语义化信息
		/*gxw-s		sb.append("\nPoi: ");// POI信息
				if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
					for (int i = 0; i < location.getPoiList().size(); i++) {
						Poi poi = (Poi) location.getPoiList().get(i);
						sb.append(poi.getName() + ";");
					}
				}
			gxw-e*/
                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("\nspeed : ");
                    sb.append(location.getSpeed());// 速度 单位：km/h
                    sb.append("\nsatellite : ");
                    sb.append(location.getSatelliteNumber());// 卫星数目
                    sb.append("\nheight : ");
                    sb.append(location.getAltitude());// 海拔高度 单位：米
                    //gxw-sb.append("\ngps status : ");
                    //gxw-sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
                    sb.append("\ndescribe : ");
                    sb.append("gps定位成功");
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    // 运营商信息
                    if (location.hasAltitude()) {// *****如果有海拔高度*****
                        sb.append("\nheight : ");
                        sb.append(location.getAltitude());// 单位：米
                    }
                    sb.append("\noperationers : ");// 运营商信息
                    sb.append(location.getOperators());
                    sb.append("\ndescribe : ");
                    sb.append("网络定位成功");
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }


                // map view 销毁后不在处理新接收的位置
                if (location == null ) {

                    Log.i(TAG, "location=null");
                    return;
                }
                mCurrentLat = location.getLatitude();
                mCurrentLon = location.getLongitude();
                Log.i(TAG, "listener lat=" + mCurrentLat + ",lng=" + mCurrentLon);


                mCurrentAccracy = location.getRadius();



                //暂时屏蔽Log.i(TAG, sb.toString());

                MyCurrentOrder currentOrder = new MyCurrentOrder(BaiduNavActivity.this);
                String itemId = currentOrder.getItemId();
                int state = currentOrder.getState();

                if ((!TextUtils.isEmpty(itemId)) && state == 2)
                {
                    MyApplication.isRecvingOrder = true;

                }
                else
                {
                    MyApplication.isRecvingOrder = false;
                    locationService.stop();
                    Log.i(TAG,"stop loc service in listener");
                }

                Message msg = new Message();
                msg.what = 0;
                Bundle b = new Bundle();
                b.putString("lat",String.valueOf(mCurrentLat));
                b.putString("lng",String.valueOf(mCurrentLon));
                msg.setData(b);
                mHandler.sendMessage(msg); //发送位置到服务端

            }
        }

        public void onConnectHotSpotMessage(String s, int i){
        }
    };


    /**
     * 传递自己的位置（志愿者的位置）到服务器
     */
    public void postMyLocation(String lat,String lng)
    {
        User user = new User(BaiduNavActivity.this);
        String token = user.getUserToken();
        long locationTime = System.currentTimeMillis();

        Log.i(TAG,"URL="+MyConstant.API_POST_MY_LOCATION+",token="+token+",latitude="+lat+",longitude="+lng);
        OkHttpUtils
                .post(MyConstant.API_POST_MY_LOCATION)//
                .tag(MyConstant.API_POST_MY_LOCATION )//
                .params("tokenId", token)//
                .params("latitude",lat)
                .params("longitude",lng)
                .params("locationTime",String.valueOf(locationTime))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        int retCode = response.code();
                        if(retCode == 200)
                        {
                            Log.i(TAG,"onSuccess 200 return："+s);
                            try
                            {
                                JSONObject postMyLoc = new JSONObject(s);
                                if(postMyLoc.getString("status").equals("1"))  //成功响应
                                {
                                    Log.i(TAG,"上传我的位置成功");
                                }

                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            MyErrorDeal.dealHttpError(response,BaiduNavActivity.this);
                            Log.i(TAG,"onSuccess "+retCode+"return: "+s);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

                        MyErrorDeal.dealHttpError(response,BaiduNavActivity.this);

                    }
                });
        return;
    }

    private void createHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what)
                {
                    case 0:       //上传自己的位置到服务端

                        Bundle b = msg.getData();
                        if(b != null)
                        {
                            String lat = b.getString("lat");
                            String lng = b.getString("lng");
                            postMyLocation(lat,lng);
                        }
                        break;
                    case 1:      //背后读取数据库位置
                       //gxw- refreshSosLocation(GET_SOSLOC_FROM_DB);

                        break;
                    case 2:
                        addMyLocationLayer(); //接单成功后且在救援中时，要不断上传志愿者的位置
                        break;
                }

                // 要做的事情
                super.handleMessage(msg);
            }
        };
    }
    public void initLocServiceAndStart()
    {

        locationService = ((MyApplication) this.getApplication()).locationService;

        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        //locationService.setLocationOption(locationService.getDefaultLocationClientOption());//重复设置这个option会导致百度定位service 停止
        locationService.start();

    }
    /**
     * 启动定位，我的位置
     */
    public void addMyLocationLayer()
    {
        // 开启定位图层
        //gxw-mBaiduMap.setMyLocationEnabled(true);
        initLocServiceAndStart();
    }
    /**
     * 接受任务单
     */
    public void receiveOrder()
    {
        User user = new User(BaiduNavActivity.this);
        String token = user.getUserToken();

        OkHttpUtils
                .post(MyConstant.API_RECEIVE_ORDER)//
                .tag(MyConstant.API_RECEIVE_ORDER)//
                .params("tokenId", token)//
                .params("itemId", taskItemId)//
                .execute(new StringDialogCallback(BaiduNavActivity.this) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        int retCode = response.code();
                        if(retCode == 200)
                        {

                            Log.i(TAG,"onSuccess 200 return："+s);
                            try
                            {
                                ReceiveOrderJson receiveOrderJson = new Gson().fromJson(s,ReceiveOrderJson.class);

                                if(receiveOrderJson.getStatus() == 1)//接单成功
                                {
                                    //登录成功
                                    dealRecvOrderOk(receiveOrderJson.getData());
                                }
                                else {
                                    //接单失败，别人已接或者自己已接
                                    String msg = receiveOrderJson.getMsg();
                                    MyErrorDeal.dealError(msg,BaiduNavActivity.this);
                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            MyErrorDeal.dealHttpError(response,BaiduNavActivity.this);
                            Log.i(TAG,"onSuccess "+retCode+"return: "+s);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

                        MyErrorDeal.dealHttpError(response,BaiduNavActivity.this);

                    }
                });
        return;
    }

    @Override
    protected void onDestroy() {

        Log.i(TAG,"onDestroy");
        MainActivity.activityList.remove(this);
        BNRouteGuideManager.getInstance().onDestroy();
        super.onDestroy();
    }
}
